//
//  HomeStackView.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/4/15.
//

import SwiftUI
import FlowStacks

enum HomeStack: Hashable,Equatable {
    case home
    case webPage(url: String)
    case addDevice
    case wifiInfo
    case scannerContainer
    case addingDevice
    case addDeviceList(peripheralIds: [UUID])
}

struct HomeStackView: View {
    @State private var routes: [Route<HomeStack>] = []
    var body: some View {
        FlowStack($routes, withNavigation: true) {
            HomeView()
                .flowDestination(for: HomeStack.self, destination: { stack in
                    switch stack {
                        case .home:
                        HomeView().navigationBarHidden(true).enableSwipeBackGesture(enable: true).toolbar(.hidden, for: .tabBar)
                        case let .webPage(url):
                        WebPageView(url: url).navigationBarHidden(true).enableSwipeBackGesture(enable: true).toolbar(.hidden, for: .tabBar)
                        case .addDevice:
                        AddDeviceView().navigationBarHidden(true).enableSwipeBackGesture(enable: true).toolbar(.hidden, for: .tabBar)
                        case .scannerContainer:
                        ScannerContainer().navigationBarHidden(true).enableSwipeBackGesture(enable: true).toolbar(.hidden, for: .tabBar)
                        case .addingDevice:
                        AddingDeviceView().navigationBarHidden(true).enableSwipeBackGesture(enable: true).toolbar(.hidden, for: .tabBar)
                        case let .addDeviceList(peripheralIds):
                        let viewModel = AddDeviceListViewModel(peripheralIDs: peripheralIds)
                        AddDeviceListView(viewModel: viewModel).navigationBarHidden(true).enableSwipeBackGesture(enable: true).toolbar(.hidden, for: .tabBar)
                        case .wifiInfo:
                            WifiInfoView(closeAction: {
                                removeRoute {
                                    if case .wifiInfo = $0 { return true }
                                    return false
                                }
                            }).onDisappear {
                                removeRoute {
                                    if case .wifiInfo = $0 { return true }
                                    return false
                                }
                            }
                        }
                })
        }
    }
    
    
    func removeRoute(where predicate: (HomeStack) -> Bool) {
        for (index, route) in routes.enumerated().reversed() {
            if predicate(route.screen) {
                routes.remove(at: index)
            }
        }
    }

}
